<?php
namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path') , EXT);

use app\admin\Controller;
use think\Exception;
use think\Loader;
use think\Config;
use think\Db;
use think\Request;
use think\Validate;

class HotelAccommodation extends Controller
{
    use \app\admin\traits\controller\Controller;
    // 方法黑名单
    protected static $blacklist = [];

    protected function filter(&$map)
    {
        if ($this->request->param("driver_user_id")) {
            $map['driver_user_id'] = ["like", "%" . $this->request->param("driver_user_id") . "%"];
        }
        if ($this->request->param("order_travel_ids")) {
            $map['order_travel_ids'] = ["like", "%" . $this->request->param("order_travel_ids") . "%"];
        }
        if ($this->request->param("check_in_date")) {
            $map['check_in_date'] = ["like", "%" . $this->request->param("check_in_date") . "%"];
        }
        if ($this->request->param("end_date")) {
            $map['end_date'] = ["like", "%" . $this->request->param("end_date") . "%"];
        }
        if ($this->request->param("route_id")) {
            $map['route_id'] = ["like", "%" . $this->request->param("route_id") . "%"];
        }
        if ($this->request->param("driver_user_id")) {
            $map['driver_user_id'] = ["like", "%" . $this->request->param("driver_user_id") . "%"];
        }
        if ($this->request->param("hotel_room_type")) {
            $map['hotel_room_type'] = ["like", "%" . $this->request->param("hotel_room_type") . "%"];
        }
        if ($this->request->param("remark")) {
            $map['remark'] = ["like", "%" . $this->request->param("remark") . "%"];
        }
    }

    //首页
    public function index()
    {

        $data=input();
        $map['is_complete'] = 0;
        //查询条件
        if ($data['id']){
            $map['id'] = ['like',"%{$data['id']}%"];
        }
        if ($data['group_id']){
            $map['group_id'] = ['like',"%{$data['group_id']}%"];
        }
        if ($data['driver_user_id']){
            // 从用户获取司机id
            $driverUserIds = Db::name('admin_user')->where('realname','like',"%{$data['driver_user_id']}%")->field('id')->select();
            if ($driverUserIds){
                $driver_user_id = '';
                foreach ($driverUserIds as $index => $driverUserId) {
                    $driver_user_id .= $driverUserId['id'].',';
                }
                $driver_user_id = rtrim($driver_user_id,',');
                $map['driver_user_id'] = ['in',$driver_user_id];
            }
        }
        if ($data['order_travel_ids']){
           $name_of_passenger = Db::name('hotel_accommodation')->where('name_of_passenger','like',"%{$data['order_travel_ids']}%")->select();
           if ($name_of_passenger) {
               $id = '';
               foreach ($name_of_passenger as $index12 => $item12) {
                   $id .= $item12['id'].',';
               }
               $map['id'] = ['in',rtrim($id,',')];
           }else{
               // 获取旅客id
               $OrderTravelIds = Db::name('order_traveler')->where('name','like',"%{$data['order_travel_ids']}%")->field('id')->select();
               if ($OrderTravelIds){
                   $order_travel_ids = '';
                   foreach ($OrderTravelIds as $index => $OrderTravelId) {
                       $order_travel_ids .= $OrderTravelId['id'].',';
                   }
                   $order_travel_ids = rtrim($order_travel_ids,',');
                   $map['order_travel_ids'] = ['in',$order_travel_ids];
               }
           }
        }
        $start_time = '';
        if ($data['check_in_date_start']){
            $start_time = "{$data['check_in_date_start']} 0:0:0"; //开始时间
            $end_time = "{$data['check_in_date_start']} 23:59:59"; // 结束时间
            $map['check_in_date'] = ['between',[strtotime($start_time),strtotime($end_time)]];
        }
        if ($data['check_in_date_end']){
            if(!$data['check_in_date_start']){
                $start_time = "{$data['check_in_date_end']} 0:0:0"; //开始时间
            }
            $end_time = "{$data['check_in_date_end']} 23:59:59"; // 结束时间
            $map['check_in_date'] = ['between',[strtotime($start_time),strtotime($end_time)]];
        }
        if ($data['unit_price']){
            $map['unit_price'] = ['like',"%{$data['unit_price']}%"];
	    }
        if ($data['route_id']){
            // 路线id
            $routeIds = Db::name('route')->where('title','like',"%{$data['route_id']}%")->field('id')->select();
            if ($routeIds){
                $route_id = '';
                foreach ($routeIds as $index => $routeId) {
                    $route_id .= $routeId['id'].',';
                }
                $route_id = rtrim($route_id,',');
                $map['route_id'] = ['in',$route_id];
 		}else{
                	$map['route_id'] = ['in',[]];
            }
        }
        if ($data['hotel_id']){
            // 从酒店获取酒店id
            $hotelIds = Db::name('hotel')->where('hotel_name','like',"%{$data['hotel_id']}%")->field('id')->select();
            if ($hotelIds){
                $hotel_id = '';
                foreach ($hotelIds as $index => $hotelId) {
                    $hotel_id .= $hotelId['id'].',';
                }
                $hotel_id = rtrim($hotel_id,',');
                $map['hotel_id'] = ['in',$hotel_id];
            }
        }
        if ($data['hotel_room_type']){
            $map['hotel_room_type']=$data['hotel_room_type'];
        }
        if ($data['remark']){
            $map['remark'] = ['like',"%{$data['remark']}%"];
        }
        if ($data['create_time']){
            $start_time = "{$data['create_time']} 0:0:0";
            $end_time = "{$data['create_time']} 23:59:59";
            $map['create_time'] = ['between',[strtotime($start_time),strtotime($end_time)]];
        }
        // 查询所有
        if ($this::$isdelete){
            $map['isdelete'] = 1;
        }else{
            $map['isdelete'] = 0;
        }
        $listRows = $this->request->param('numPerPage') ?: Config::get("paginate.list_rows");
        $list = Db::name('hotel_accommodation')->where($map)->order('id','desc')->paginate($listRows, false, ['query' => $this->request->get()]);
        $list_data = $list->toArray();
        $listData = $list_data['data'];
        if ($list_data['data']){
            foreach ($list_data['data'] as $ldk=>$ldv){
                //查找客人姓名
                $travelers=Db::name("order_traveler")
                    ->where('id','in',$ldv['order_travel_ids'])
                    ->select();
                $list_data['data'][$ldk]['booking_people_num'] = Db::name("order_traveler")
                    ->where('id','in',$ldv['order_travel_ids'])
                    ->count();
                $traveler_name = '';
                if ($travelers){
                    foreach ($travelers as $index => $traveler) {
                        $traveler_name .= "{$traveler['id']}:{$traveler['name']}+";
                    }
                    $traveler_name = rtrim($traveler_name,'+');
                }
                $list_data['data'][$ldk]['booking_people_name'] = $traveler_name;
            }
        }
//         获取结算价格
//        if ($listData){
//            foreach ($listData as $index02 => $listDatum) {
//                $ret = self::getSettlementPrice($listDatum); // 接受结算价格的统计
//                $listData[$index02]['date'] = $ret['date'];
//                $listData[$index02]['price'] = $ret['price'];
//            }
//        }
        // 模板赋值显示
        $map_hotel_room_type['isdelete']=0;

        $hotel_room_type=Db::name('hotel_room_type')
            ->where($map_hotel_room_type)
            ->select();
        $count = $list->count();
        $this->view->assign('hotel_room_type',$hotel_room_type);
        $this->view->assign('list',$list);
        $this->view->assign('searchCondition',$data);
        $this->view->assign('list_data',$list_data['data']);
        $this->view->assign('listData',$listData);
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());
        $this->view->assign('count',$count);
        return $this->view->fetch();

    }

    //编辑
    public function edit(Request $request)
    {
        if ($request->isPost()){
            $postData = $request->post();
            // 验证数据
            $rule = [
                'id' => 'require',
                'check_in_date' => 'require',
                'end_date' => 'require',
                'hotel_id' => 'require',
                'hotel_room_type' => 'require',
            ];
            $message = [
                'id.require' => '缺少必要的参数id',
                'check_in_date.require' => '入住日期不能为空',
                'end_date.require' => '结束日期不能为空',
                'hotel_id.require' => '酒店名称不能为空',
                'hotel_room_type.require' => '酒店房型不能为空',
            ];
            $valdate = new Validate($rule, $message);
            $result = $valdate->check($postData);
            if (!$result){
                return ajax_return_adv_error($valdate->getError());
            }
            if ($postData['end_date'] < $postData['check_in_date']){
                return ajax_return_adv_error('开始日期不能大于结束日期');
            }
            // 获取之前的住宿信息
            $oldHotelInfos = Db::name('hotel_accommodation')->where('id',$postData['id'])->find();
            if (!$oldHotelInfos){
                return ajax_return_adv_error('不存在该住宿信息');
            }
            // 处理旧的酒店记录
            $oldDate = self::getDate($oldHotelInfos['check_in_date'],$oldHotelInfos['end_date'],2);
            foreach ($oldDate as $index => $item) {
                $find = Db::name('room_consumption')->where('hotel_id',$oldHotelInfos['hotel_id'])
                                                        ->where('hotel_room_type_id',$oldHotelInfos['hotel_room_type'])
                                                        ->where('date_of_stay',$item)
                                                        ->find();
                if (!$find){
                    Db::name('room_consumption')->strict(false)->insert([
                        'hotel_id' => $oldHotelInfos['hotel_id'],
                        'hotel_room_type_id' => $oldHotelInfos['hotel_room_type'],
                        'date_of_stay' => $item,
                        'create_time' => time(),
                        'num' => 0,
                    ]);
                }
                // 更新房型记录
                $up = Db::name('room_consumption')->where('hotel_id',$oldHotelInfos['hotel_id'])
                                                        ->where('hotel_room_type_id',$oldHotelInfos['hotel_room_type'])
                                                        ->where('date_of_stay',$item)
                                                        ->setDec('num');//自减1
                if (!$up){
                    return ajax_return_adv_error('处理旧的房型失败');
                }
            }
            // 添加新的酒店住宿记录
            $newDate = self::getDate($postData['check_in_date'],$postData['end_date'],1);
            foreach ($newDate as $index01 => $item01) {
                $find = Db::name('room_consumption')->where('hotel_id',$postData['hotel_id'])
                                                            ->where('hotel_room_type_id',$postData['hotel_room_type'])
                                                            ->where('date_of_stay',$item01)
                                                            ->find();
                if (!$find){
                    Db::name('room_consumption')->strict(false)->insertGetId([
                        'hotel_id' => $postData['hotel_id'],
                        'hotel_room_type_id' => $postData['hotel_room_type'],
                        'date_of_stay' => $item01,
                        'create_time' => time(),
                        'num' => 0,
                    ]);
                }
                // 更新房型记录
                $up = Db::name('room_consumption')->where('hotel_id',$postData['hotel_id'])
                                                    ->where('hotel_room_type_id',$postData['hotel_room_type'])
                                                    ->where('date_of_stay',$item01)
                                                    ->setInc('num');//自增1
                if (!$up){
                    return ajax_return_adv_error('添加新的住房记录失败');
                }
            }

            // 更新住宿列表信息
            $postData['check_in_date'] = strtotime($postData['check_in_date']);
            $postData['end_date'] = strtotime($postData['end_date']);
            $updateCount = Db::name('hotel_accommodation')->strict(false)->update($postData);
            if ($updateCount){
                return ajax_return_adv('更新成功');
            }else{
                return ajax_return_adv_error('更新失败');
            }
        }else{
            $data = input();
            if (!$data['id']) {
                return ajax_return_adv_error('缺少参数');
            }
            // 查找该信息
            $vo = Db::name('hotel_accommodation')->where('id',$data['id'])->find();
            // 查询
            $hotel = Db::name('hotel')->where('isdelete', 0)->select();
            $route = Db::name('route')->where('isdelete', 0)->select();
            $admin_user = Db::name('admin_user')->where('id',$vo['driver_user_id'])->select();
            $hotel_room_type = Db::name('hotel_room_type')->where('isdelete', 0)->select();
            $listRows = $this->request->param('numPerPage') ?: Config::get("paginate.list_rows");
            $list = Db::name('hotel_accommodation')->where('id',$data['id'])->paginate($listRows, false, ['query' => $this->request->get()]);
            $list_data = $list->toArray();
            if ($list_data['data']){
                foreach ($list_data['data'] as $ldk=>$ldv){
                    //查找客人姓名
                    $travelers=Db::name("order_traveler")
                        ->where('id','in',$ldv['order_travel_ids'])
                        ->select();
                    $traveler_name = '';
                    if ($travelers){
                        foreach ($travelers as $index => $traveler) {
                            $traveler_name .= "{$traveler['id']}:{$traveler['name']}+";
                        }
                        $traveler_name = rtrim($traveler_name,'+');
                    }

                    $list_data['data'][$ldk]['booking_people_name'] = $traveler_name;
                }
            }
            $this->view->assign('hotel',$hotel);
            $this->view->assign('route',$route);
            $this->view->assign('admin_user',$admin_user);
            $this->view->assign('hotel_room_type',$hotel_room_type);
            $this->view->assign('list_data',$list_data['data']);
            $this->view->assign('vo',$vo);
            return $this->view->fetch();
        }
    }


    /**
     * 导出数据到excel
     */
    public function get_excel(Request $request)
    {
        $data = input();
        Vendor('PHPExcel.PHPExcel');
        Vendor('PHPExcel.PHPExcel.WorkSheet.Drawing');
        Vendor('PHPExcel.PHPExcel.Writer.Excel2007');
        //实例化
        $export_excel = new \PHPExcel();
        //设置文档属性
        $writer = \PHPExcel_IOFactory::createWriter($export_excel,'Excel2007');
        //设置内容
        $export_sheet = $export_excel->getActiveSheet();
        for ($l = 0; $l < 26; $l++) {
            $letter[] = chr($l+65);
        }
        $countChr = count($letter);
        for ($j = 0; $j < $countChr; $j++) {
            for ($k = 0; $k < $countChr; $k++) {
                $letter[] = $letter[$j].$letter[$k];
            }
        }
        $tableHeader = ['出行路线','住宿派单号','司机姓名','入住日期','组合旅客姓名','数量','酒店名称','酒店房型','房量','单价','房费合计','备注'];
        $li_length = count($letter);//设置单元格的宽度
        for ($li=0;$li<$li_length;$li++){
            switch ($letter[$li]){
                case 'A':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);break;
                case 'B':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);break;
                case 'C':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);break;
                case 'D':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);break;
                case 'E':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);break;
                case 'G':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);break;
                case 'H':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);break;
                case 'I':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);break;
                case 'J':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);break;
                case 'K':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);break;
                case 'L':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);break;
                default:
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);
            }
        }
        $tableLength = count($tableHeader);
        for ($i = 0; $i < $tableLength; $i++){
            $export_sheet->setCellValue("$letter[$i]1","$tableHeader[$i]");
        }


        $map['isdelete'] = 0;
        $map['id'] = ['in',$data['ids']];
        //查询要填充表格数据
        $lists = Db::name('hotel_accommodation')->where($map)->order('id','desc')->select();
        //字段转换
        foreach ($lists as $lk=>$lv) {
            if(!empty($lv['route_id'])){
                $title =  Db::name('route')->where('id',$lv['route_id'])->value('title');
            }
            if(!empty($lv['driver_user_id'])){
                $realname = Db::name('admin_user')->where('id',$lv['driver_user_id'])->value('realname');
            }
            //查找客人姓名
            if(!empty($lv['order_travel_ids'])){
                $travelers=Db::name("order_traveler")
                    ->where('id','in',$lv['order_travel_ids'])
                    ->select();
                $traveler_name = '';
                if ($travelers){
                    foreach ($travelers as $index => $traveler) {
                        $traveler_name .= "{$traveler['id']}:{$traveler['name']}+";
                    }
                    $traveler_name = rtrim($traveler_name,'+');
                }
            }
            $booking_people_num = Db::name("order_traveler")
                ->where('id','in',$lv['order_travel_ids'])
                ->count();//客人数量
            if(!empty($lv['hotel_id'])){
                $hotel_name = Db::name('hotel')->where('id',$lv['hotel_id'])->value('hotel_name');
            }
            if(!empty($lv['hotel_room_type'])){
                $room_name =  Db::name('hotel_room_type')->where('id',$lv['hotel_room_type'])->value('room_name');
            }
            $num = round(($lv['end_date']-$lv['check_in_date'])/3600/24);
            $heji = (int)$num * (int)$lv['unit_price'];
            $user_name = Db::name('admin_user')->where('id',$lv['driver_user_id'])->value('realname');
            $list[$lk]['title'] = empty($title) ? '' : $title; //路线名称
            $list[$lk]['id'] = empty($lv['id']) ? '' : $lv['id']; //住宿派单号
            $list[$lk]['realname'] = empty($realname) ? '' : $realname; //司机
            $list[$lk]['check_in_date'] = empty($lv['check_in_date']) ? '' : date('Y-m-d',$lv['check_in_date']); //出发时间
            $list[$lk]['traveler_name'] = empty($traveler_name) ? '' : $traveler_name; //客人姓名
            $list[$lk]['booking_people_num'] = empty($booking_people_num) ? '' : $booking_people_num; //数量
            $list[$lk]['hotel_name'] = empty($hotel_name) ? '' : $hotel_name; //酒店名称
            $list[$lk]['room_name'] = empty($room_name) ? '' : $room_name; //酒店类型
            $list[$lk]['num'] = empty($num) ? '' : $num; //房量
            $list[$lk]['unit_price'] = empty($lv['unit_price']) ? '' : $lv['unit_price']; //单价
            $list[$lk]['heji'] = empty($heji) ? '' : $heji; //房费合计
            $list[$lk]['remark'] = empty($lv['remark']) ? '' : $lv['remark']; //备注
        }

        //定义table键
        if (!empty($list)){
            $tableKey = array_keys($list[0]);
            //填充表格信息
            $tableKeyLength = count($tableKey);
            foreach ($list as $tk=>$tv){
                $tk += 2;
                for ($i = 0; $i < $tableKeyLength; $i++){
                    $export_sheet->setCellValue("$letter[$i]".$tk,$tv[$tableKey[$i]]);
                }
            }
        }
        $fileName = date('YmdHis',time())."酒店管理-已分配住宿旅客数据.xls";
        $fileName = iconv('utf-8','gb2312',$fileName);
        ob_end_clean();
        if ($request->isGet()){
            header('Content-Type:application/force-download');
            header('Content-Type:application/octet-stream');
            header('Content-Type:application/download');
            header('Content-Disposition:inline;filename='.$fileName);
            header('Content-Transfer-Encoding:binary');
            header('Cache-Control:must-revalidate,post-check=0');
            header('Pragma:no-cache');
            $writer->save('php://output');
            exit();
        }else{
            // 保存文件到服务器上
            $path = ROOT_PATH."public/excel";
            // 判断文件是否存在
            if (!file_exists($path)){
                mkdir($path,0777,true);
            }
            $fileName = iconv('gb2312','utf-8',$fileName);
            $file = $path."/{$fileName}";
            $writer->save($file);
            $url =$request->domain()."/excel/{$fileName}";
            return ajax_return_adv($url,'','','','','',5);
        }
    }

    /**
     * 结算导出excel
     */
    public function settlement_excel(Request $request){
        $data = input();
        Vendor('PHPExcel.PHPExcel');
        Vendor('PHPExcel.PHPExcel.WorkSheet.Drawing');
        Vendor('PHPExcel.PHPExcel.Writer.Excel2007');
        //实例化
        $export_excel = new \PHPExcel();
        //设置文档属性
        $writer = \PHPExcel_IOFactory::createWriter($export_excel,'Excel2007');
        //设置内容
        $export_sheet = $export_excel->getActiveSheet();
        for ($l = 0; $l < 26; $l++) {
            $letter[] = chr($l+65);
        }
        $countChr = count($letter);
        for ($j = 0; $j < $countChr; $j++) {
            for ($k = 0; $k < $countChr; $k++) {
                $letter[] = $letter[$j].$letter[$k];
            }
        }
        if($data['is_close'] == 1){
            //未结算
            $tablename = '未结算';
            $tableHeader = ['住宿单号','酒店名称','路线名称','司机姓名','组合旅客姓名','入住日期','退房日期','账号名称','账号','开户行','酒店房型','房型单价','房型使用量','订金','总价','结算状态','备注'];

        }elseif($data['is_close'] == 2){
            //申请结算
            $tablename = '申请结算';
            $tableHeader = ['住宿单号','酒店名称','路线名称','司机姓名','组合旅客姓名','入住日期','退房日期','账号名称','账号','开户行','酒店房型','房型单价','房型使用量','订金','总价','结算状态','备注'];

        }elseif($data['is_close'] == 3){
            //结算驳回
            $tablename = '结算驳回';
            $tableHeader = ['住宿单号','酒店名称','路线名称','司机姓名','组合旅客姓名','入住日期','退房日期','账号名称','账号','开户行','酒店房型','房型单价','房型使用量','订金','总价','驳回原因','备注'];
        }elseif($data['is_close'] == 4){
            //已结算
            $tablename = '已结算';
            $tableHeader = ['住宿单号','酒店名称','路线名称','司机姓名','组合旅客姓名','入住日期','退房日期','账号名称','账号','开户行','酒店房型','房型单价','房型使用量','订金','总价','结算方式','结算金额','备注'];

        }
        $li_length = count($letter);//设置单元格的宽度
        for ($li=0;$li<$li_length;$li++){
            switch ($letter[$li]){
                case 'A':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);break;
                case 'B':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);break;
                case 'C':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);break;
                case 'D':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);break;
                case 'E':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);break;
                case 'G':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);break;
                case 'H':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);break;
                case 'I':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);break;
                case 'J':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);break;
                case 'K':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);break;
                case 'L':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);break;
                default:
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);
            }
        }
        $tableLength = count($tableHeader);
        for ($i = 0; $i < $tableLength; $i++){
            $export_sheet->setCellValue("$letter[$i]1","$tableHeader[$i]");
        }


        $map['isdelete'] = 0;
        $map['id'] = ['in',$data['ids']];
        //查询要填充表格数据
        $lists = Db::name('hotel_accommodation')->where($map)->order('id','desc')->select();
        //字段转换
        foreach ($lists as $lk=>$lv) {
            $list[$lk]['id'] = $lv['id'];
            //酒店姓名
            if(!empty($lv['hotel_id'])){
                $hotel_name = Db::name('hotel')->where('id',$lv['hotel_id'])->value('hotel_name');
            }
            $list[$lk]['hotel_name'] = empty($hotel_name) ? '' : $hotel_name;
            //路线名称
            if(!empty($lv['route_id'])){
                $title = Db::name('route')->where('id',$lv['route_id'])->value('title');
            }
            $list[$lk]['title'] = empty($title) ? '' : $title;
            //司机姓名
            if(!empty($lv['driver_user_id'])){
                $realname = Db::name('admin_user')->where('id',$lv['driver_user_id'])->value('realname');
            }
            $list[$lk]['realname'] = empty($realname) ? '' : $realname;
            //查找客人姓名
            if(!empty($lv['order_travel_ids'])){
                $travelers=Db::name("order_traveler")
                    ->where('id','in',$lv['order_travel_ids'])
                    ->select();
                $traveler_name = '';
                if ($travelers){
                    foreach ($travelers as $index => $traveler) {
                        $traveler_name .= "{$traveler['id']}:{$traveler['name']}+";
                    }
                    $traveler_name = rtrim($traveler_name,'+');
                }
            }
            $list[$lk]['traveler_name'] = empty($traveler_name) ? '' : $traveler_name;
            //入住日期
            $list[$lk]['check_in_date'] = empty($lv['check_in_date']) ? '' : date('Y-m-d',$lv['check_in_date']);
            //退房日期
            $list[$lk]['end_date'] = empty($lv['end_date']) ? '' : date('Y-m-d',$lv['end_date']);
            //账号名称
            $list[$lk]['account_name'] = empty($lv['account_name']) ? '' : $lv['account_name'];
            //账号
            $list[$lk]['account'] = empty($lv['account']) ? '' : $lv['account'];
            //开户行
            $list[$lk]['account_bank'] = empty($lv['account_bank']) ? '' : $lv['account_bank'];
            //酒店房型
            if(!empty($lv['hotel_room_type'])){
                $room_name = Db::name('hotel_room_type')->where('id',$lv['hotel_room_type'])->value('room_name');
            }
            $list[$lk]['room_name'] = empty($room_name) ? '' : $room_name;
            //房型单价
            $list[$lk]['unit_price'] = empty($lv['unit_price']) ? 0 : $lv['unit_price'];
            //房型使用量
            if($lv['end_date'] && $lv['check_in_date']){
                $hotel_room_count = round(($lv['end_date']-$lv['check_in_date'])/3600/24);
            }
            $list[$lk]['hotel_room_count'] = empty($hotel_room_count) ? '' : $hotel_room_count;
            //订金
            $list[$lk]['subscription'] = empty($lv['subscription']) ? '' : $lv['subscription'];
            //总价
            $list[$lk]['total_price'] = empty($lv['total_price']) ? '' : $lv['total_price'];
            if($data['is_close'] == 3){//驳回原因
                $list[$lk]['reject_remark'] = empty($lv['reject_remark']) ? '' : $lv['reject_remark'];
            }elseif($data['is_close'] != 4){//结算状态
                $list[$lk]['is_settlement'] = empty($lv['is_settlement']) ? '未结算' : '已结算';
            }elseif($data['is_close'] == 4){
                $list[$lk]['settlement_mode'] = empty($lv['settlement_mode']) ? '' : $lv['settlement_mode'];//结算方式
                $list[$lk]['settlement_money'] = empty($lv['settlement_money']) ? '' : $lv['settlement_money'];//结算金额
            }
            $list[$lk]['remark'] = empty($lv['remark']) ? '' : $lv['remark']; //备注
        }
        //定义table键
        if (!empty($list)){
            $tableKey = array_keys($list[0]);
            //填充表格信息
            $tableKeyLength = count($tableKey);
            foreach ($list as $tk=>$tv){
                $tk += 2;
                for ($i = 0; $i < $tableKeyLength; $i++){
                    $export_sheet->setCellValue("$letter[$i]".$tk,$tv[$tableKey[$i]]);
                }
            }
        }
        $fileName = date('YmdHis',time())."酒店管理-$tablename 数据.xls";
        $fileName = iconv('utf-8','gb2312',$fileName);
        ob_end_clean();
        if ($request->isGet()){
            header('Content-Type:application/force-download');
            header('Content-Type:application/octet-stream');
            header('Content-Type:application/download');
            header('Content-Disposition:inline;filename='.$fileName);
            header('Content-Transfer-Encoding:binary');
            header('Cache-Control:must-revalidate,post-check=0');
            header('Pragma:no-cache');
            $writer->save('php://output');
            exit();
        }else{
            // 保存文件到服务器上
            $path = ROOT_PATH."public/excel";
            // 判断文件是否存在
            if (!file_exists($path)){
                mkdir($path,0777,true);
            }
            $fileName = iconv('gb2312','utf-8',$fileName);
            $file = $path."/{$fileName}";
            $writer->save($file);
            $url =$request->domain()."/excel/{$fileName}";
            return ajax_return_adv($url,'','','','','',5);
        }
    }

    /**
     * 获取结算价格信息
     */
    public static function getSettlementPrice($data)
    {
//        dump($data);
        // 获取日期
        // 根据结算价格的入住日期、结束日期，从房间记录查询酒店那段时间的所有记录
        $tian = round(($data['end_date']-$data['check_in_date'])/3600/24);
        $check_in_date = date('Y-m-d',$data['check_in_date']);
        // 把入住日期与退房日期的相差天数
        $date = [$check_in_date];
        for ($i=1; $i<= $tian; $i++){
            array_push($date,date("Y-m-d",strtotime("+{$i} day", $data['check_in_date'])));//添加的
        }
        $price = 0;
        $dateArr = []; // 时间数组
        foreach ($date as $index => $item) {
            $map['start_time'] = ['<=',$item];
            $map['end_time'] = ['>=',$item];
            $hotelTimePrice = Db::name('hotel_time_price')->where('hotel_id',$data['hotel_id'])->where($map)->order('id','desc')->find();
            if ($hotelTimePrice){
                // 查询酒店房型房价
                $roomPrice = Db::name('hotel_room_price')->where('hotel_id',$data['hotel_id'])
                                                  ->where('hotel_time_price_id',$hotelTimePrice['id'])
                                                  ->where('room_type_id',$data['hotel_room_type'])
                                                  ->value('room_price');
                if ($roomPrice){
                    $dateArr[] = [
                        'date' => $item,
                        'price' => $roomPrice,
                    ];
                }else{ // 该酒店该房型该日期没有结算价格
                    $dateArr[] = [
                        'date' => $item,
                        'price' => 0,
                    ];
                }
            }else{ // 该酒店该日期没有结算价格
                $dateArr[] = [
                    'date' => $item,
                    'price' => 0,
                ];
            }
        }
        // 统计没有该酒店没有价格的日期
        $dateStr = '';
        // 统计结算价格
        $totalPrice = 0;
        foreach ($dateArr as $index01 => $item01) {
            if (empty($item01['price'])){
                $dateStr .= $item01['date'].',';
            }else{
                $totalPrice += $item01['price'];
            }
        }
        // 组装结算价格
        $settlementPrice = [
            'date' => rtrim($dateStr,','),
            'price' => $totalPrice,
        ];
        return $settlementPrice;
    }

    /**
     * 确认结算
     */
    public function settlement(Request $request)
    {
        if ($request->isPost()){
            $postData = $request->post();
            // 验证数据
            if (!$postData['id']){
                return ajax_return_adv_error('缺少id');
            }
            if (!$postData['val']){
                return ajax_return_adv_error('缺少必填参数');
            }
            // 查找住宿列表
            $find = Db::name('hotel_accommodation')->where('id',$postData['id'])->find();
            if (!$find){
                return ajax_return_adv_error('不存在该住宿列表信息');
            }
            if ($find['is_complete'] == 1){
                return ajax_return_adv_error('已完成');
            }
            $up = Db::name('hotel_accommodation')->where('id',$postData['id'])->update(['is_complete'=>1]);
            if ($up){
                return ajax_return_adv('更新成功');
            }else{
                return ajax_return_adv_error('更新失败');
            }
        }
    }

    /**
     * 添加住宿记录
     */
    public function add(Request $request)
    {
        if ($request->isPost()){
            $postData = $request->post();
            // 验证数据
            $rule = [
                'name_of_passenger' => 'require',
                'check_in_date' => 'require',
                'end_date' => 'require',
                'hotel_id' => 'require',
                'hotel_room_type' => 'require',
            ];
            $message = [
                'name_of_passenger.require' => '旅客组合姓名不能为空',
                'check_in_date.require' => '入住日期不能为空',
                'end_date.require' => '结束日期不能为空',
                'hotel_id.require' => '酒店名称不能为空',
                'hotel_room_type.require' => '酒店房型不能为空',
            ];
            $valdate = new Validate($rule, $message);
            $result = $valdate->check($postData);
            if (!$result){
                return ajax_return_adv_error($valdate->getError());
            }
            if ($postData['end_date'] < $postData['check_in_date']){
                return ajax_return_adv_error('开始日期不能大于结束日期');
            }
            // 获取开始日期和结束日期
            // 根据结算价格的入住日期、结束日期，从房间记录查询酒店那段时间的所有记录
            $tian = round((strtotime($postData['end_date'])-strtotime($postData['check_in_date']))/3600/24);;
            // 把入住日期与退房日期的相差天数
            $date = [$postData['check_in_date']];
            for ($i=1; $i<= $tian; $i++){
                array_push($date,date("Y-m-d",strtotime("+{$i} day",strtotime("{$postData['check_in_date']}"))));//添加的
            }
            // 添加酒店的房型记录
            $map['hotel_id'] = $postData['hotel_id'];
            $map['hotel_room_type_id'] = $postData['hotel_room_type'];
            foreach ($date as $index => $item) {
                $find = Db::name('room_consumption')->where($map)->where('date_of_stay',$item)->find();
                if (!$find){
                    $map['date_of_stay'] = $item;
                    $map['create_time'] = time();
                    $map['num'] = 0;
                    $addId = Db::name('room_consumption')->strict(false)->insertGetId($map);
                    logs('addzhusu',$addId);
                    unset($map['date_of_stay']);
                    unset($map['create_time']);
                }
                // 更新数据
                $up = Db::name('room_consumption')->where($map)->where('date_of_stay',$item)->setInc('num');
                logs('addzhusu',$up);
                logs('addzhusu',Db::name('room_consumption')->getLastSql());
                if (!$up){
                    return ajax_return_adv_error('添加房型记录失败');
                }
            }
            // 添加住宿旅客信息
            $postData['create_time'] = time();
            $postData['end_date'] = strtotime($postData['end_date']);
            $postData['check_in_date'] = strtotime($postData['check_in_date']);
            $addId = Db::name('hotel_accommodation')->strict(false)->insertGetId($postData);
            if ($addId){
                return ajax_return_adv('添加成功');
            }else{
                return ajax_return_adv_error('添加失败');
            }
        }else{
            // 查找旅游路线
            $route = Db::name('route')->where('isdelete', 0)->select();
            // 查找所有酒店
            $hotel = Db::name('hotel')->where('isdelete', 0)->select();
            return view('',compact('route','hotel'));
        }
    }

    /**
     * 获取酒店房型
     */
    public function getRoomType()
    {
        $data = input();
        if (!$data['hotel_id']){
            return ajax_return_adv_error('缺少必要的参数');
        }
        // 查找房型
        $roomTypes = Db::name('room_hotel_number')->where('hotel_id',$data['hotel_id'])->select();
        if ($roomTypes){
            foreach ($roomTypes as $index => $item) {
                // 查找房型的名称
                $room_name = Db::name('hotel_room_type')->where('id',$item['room_type_id'])->value('room_name');
                if ($room_name){
                    $roomTypes[$index]['room_name'] = $room_name;
                }else{
                    $roomTypes[$index]['room_name'] = '该房型已删除';
                }
            }
            return ajax_return_adv('获取数据成功','','','','',$roomTypes,5);
        }else{
            return ajax_return_adv_error('获取房型失败');
        }
    }

    /**
     * 获取日期
     * @param $start
     * @param $end_type
     */
    public static function getDate($start_time,$end_time,$geshi)
    {
        if ($geshi == 1){
            $start_time = strtotime($start_time);
            $end_time = strtotime($end_time);
            $start = date('Y-m-d',$start_time);
        }else{
            $start = date('Y-m-d',$start_time);
        }
        $tian = round(($end_time-$start_time)/3600/24);;
        // 把入住日期与退房日期的相差天数
        $date = [$start];
        for ($i=1; $i<= $tian; $i++){
            array_push($date,date("Y-m-d",strtotime("+{$i} day",strtotime("{$start}"))));//添加的
        }
        return $date;
    }

    /**司机详细资料**/
    public function details()
    {
        $data = input();

        $vo = Db::name('driver')->where('user_id', $data['driver_user_id'])->find();
        if (!$vo){
            return ajax_return_adv_error('不存在该司机信息');
        }
        $users = Db::name('admin_user')->where('id',$vo['user_id'])->find();
        if ($users['id']){
            $users['user_id'] = $users['id'];
            unset($users['id']);
        }
        if (!$users){
            return ajax_return_adv_error('不存在该司机的用户信息',1);
        }
        //查询司机等级
        $driverRank = Db::name('driver_rank')->where('id',$vo['driver_rank_id'])->find();
        if ($driverRank){
            $vo['driver_rank_id'] = $driverRank['name'];
        }else{
            $vo['driver_rank_id'] = '新手';
        }
        $this->view->assign('users', $users);
        $this->view->assign('vo', $vo);
        return $this->view->fetch('details');
    }

    /**
     * 结算模块列表
     */
    public function no_settlement(Request $request){
        $data=input();
        if($data['is_close'] ==1){
            //查询未结算
            $map['is_settlement'] = 0;
            $map['is_complete'] = 1;
            $map['is_apply_settlement'] = 0;
            $this->view->assign('is_close',1);
        } elseif($data['is_close'] == 2) {
            //查询申请结算
            $map['is_settlement'] = 0;
            $map['is_apply_settlement'] = 1;
            $this->view->assign('is_close',2);
        } elseif($data['is_close'] == 3) {
            //结算驳回
            $map['is_reject'] = 1;
            $map['is_settlement'] = 0;
            $this->view->assign('is_close',3);
        }elseif($data['is_close'] == 4){
            //已结算
            $map['is_settlement'] = 1;
            $this->view->assign('is_close',4);
        }

        //查询条件
        if ($data['group_id']){
            $map['group_id'] = $data['group_id'];
        }
        //账户名称
        if($data['account_name']){
            $map['account_name'] = ['like',"%{$data['account_name']}%"];
        }
        //账号
        if($data['account']){
            $map['account'] = ['like',"%{$data['account']}%"];
        }
        //开行户
        if($data['account_bank']){
            $map['account_bank'] = ['like',"%{$data['account_bank']}%"];
        }
        //司机名称
        if ($data['driver_user_id']){
            // 从用户获取司机id
            $driverUserIds = Db::name('admin_user')->where('realname','like',"%{$data['driver_user_id']}%")->field('id')->select();
            if ($driverUserIds){
                $driver_user_id = [];
                foreach ($driverUserIds as $index => $driverUserId) {
                    $driver_user_id[] = $driverUserId['id'];
                }
                $map['driver_user_id'] = ['in',$driver_user_id];
            }
        }
        //房型单价
        if($data['unit_price']){
            $map['unit_price'] = $data['unit_price'];
        }
        //旅客名称
        if ($data['order_travel_ids']){
            $order_id = Db::name('order_traveler')->where('name','like',"%{$data['order_travel_ids']}%")->field('id')->select();
            foreach ($order_id as $k => $v){
                $oids[] = $v['id'];
            }
            if(!empty($oids)){
                $ho = Db::name('hotel_accommodation')->where('is_apply_settlement',0)->field('id,order_travel_ids')->select();
                foreach ($ho as $k => $v){
                    $ido = explode(',',$v['order_travel_ids']);
                    foreach ($ido as $kl => $vl){
                        if(in_array($vl,$oids)){
                            $ida[] = $v['id'];
                        }
                    }
                }
            }
            if(!empty($ida)){
                $map['id'] = ['in',$ida];
            }else{
                $map['id'] = 'on';
            }
        }
        //电话号码
        if($data['phone']){
            $order_id = Db::name('order_traveler')->where('phone','like',"%{$data['phone']}%")->field('id')->select();
            foreach ($order_id as $k => $v){
                $o_ids[] = $v['id'];
            }
            if(!empty($o_ids)){
                if(isset($oids)){
                   $oidm = array_intersect($o_ids,$oids);
                }
                $ho = Db::name('hotel_accommodation')->where('is_apply_settlement',0)->field('id,order_travel_ids')->select();
                foreach ($ho as $k => $v){
                    $ido = explode(',',$v['order_travel_ids']);
                    foreach ($ido as $kl => $vl){
                        if(in_array($vl,$oidm)){
                            $ida[] = $v['id'];
                        }
                    }
                }
            }
            if(!empty($ida)){
                $map['id'] = ['in',$ida];
            }else{
                $map['id'] = 'on';
            }
        }
        //出行日期
        if($data['check_in_date'] && $data['end_date']){
            $map['check_in_date'] = array("between",[strtotime($data['check_in_date']." 00:00:00"),strtotime($data['end_date']." 23:59:59")]);
        }elseif($data['check_in_date']){
            $map['check_in_date'] = array("between",[strtotime($data['check_in_date']." 00:00:00"),strtotime($data['check_in_date']." 23:59:59")]);
        }elseif($data['end_date']){
            $map['check_in_date'] = array("between",[strtotime($data['end_date']." 00:00:00"),strtotime($data['end_date']." 23:59:59")]);
        }
        //路线名称
        if ($data['route_id']){
            // 路线id
            $routeIds = Db::name('route')->where('title','like',"%{$data['route_id']}%")->field('id')->select();
            if ($routeIds){
                $route_id = [];
                foreach ($routeIds as $index => $routeId) {
                    $route_id[] = $routeId['id'];
                }
                $map['route_id'] = ['in',$route_id];
            }
        }
        //酒店名称
        if ($data['hotel_id']){
            // 从酒店获取酒店id
            $hotelIds = Db::name('hotel')->where('hotel_name','like',"%{$data['hotel_id']}%")->field('id')->select();
            if ($hotelIds){
                $hotel_id = '';
                foreach ($hotelIds as $index => $hotelId) {
                    $hotel_id .= $hotelId['id'].',';
                }
                $hotel_id = rtrim($hotel_id,',');
                $map['hotel_id'] = ['in',$hotel_id];
            }
        }
        //酒店房型
        if ($data['hotel_room_type']){
            $map['hotel_room_type']=$data['hotel_room_type'];
        }
//        if ($data['remark']){
//            $map['remark'] = ['like',"%{$data['remark']}%"];
//        }
//        if ($data['create_time']){
//            $start_time = "{$data['create_time']} 0:0:0";
//            $end_time = "{$data['create_time']} 23:59:59";
//            $map['create_time'] = ['between',[strtotime($start_time),strtotime($end_time)]];
//        }
//        if ($data['is_settlement'] == 1){
//            $map['is_settlement'] = 1;
//        }elseif ($data['is_settlement'] == 2){
//            $map['is_settlement'] = 0;
//        }
        // 查询所有
        if ($this::$isdelete){
            $map['isdelete'] = 1;
        }else{
            $map['isdelete'] = 0;
        }
        $listRows = $this->request->param('numPerPage') ?: Config::get("paginate.list_rows");
        $list = Db::name('hotel_accommodation')->where($map)->order('id','desc')->paginate($listRows, false, ['query' => $this->request->get()]);
        $list_data = $list->toArray();
        $listData = $list_data['data'];
        if ($list_data['data']){
            foreach ($list_data['data'] as $ldk=>$ldv){
                //查找客人姓名
                $travelers=Db::name("order_traveler")
                    ->where('id','in',$ldv['order_travel_ids'])
                    ->select();
                $traveler_name = '';
                if ($travelers){
                    foreach ($travelers as $index => $traveler) {
                        $traveler_name .= "{$traveler['id']}:{$traveler['name']}+";
                    }
                    $traveler_name = rtrim($traveler_name,'+');
                }

                $list_data['data'][$ldk]['booking_people_name'] = $traveler_name;
            }
        }
        // 获取结算价格
        if ($listData){
            foreach ($listData as $index02 => $listDatum) {
                $ret = self::getSettlementPrice($listDatum); // 接受结算价格的统计
                $listData[$index02]['date'] = $ret['date'];
                $listData[$index02]['price'] = $ret['price'];
                $maps['start_time'] = ['<=',$listDatum['check_in_date']];
                $maps['end_time'] = ['>=',$listDatum['end_date']];
                $hotelTimePrice = Db::name('hotel_time_price')->where('hotel_id',$data['hotel_id'])->where($maps)->order('id','desc')->find();
                $listData[$index02]['room_price'] = Db::name('hotel_room_price')->where('hotel_id',$listDatum['hotel_id'])
                    ->where('hotel_time_price_id',$hotelTimePrice['id'])
                    ->where('room_type_id',$listDatum['hotel_room_type'])
                    ->value('room_price');
            }
        }
        // 模板赋值显示
        $map_hotel_room_type['isdelete']=0;

        $hotel_room_type=Db::name('hotel_room_type')
            ->where($map_hotel_room_type)
            ->select();
        $count = $list->count();
        $this->view->assign('hotel_room_type',$hotel_room_type);
        $this->view->assign('list',$list);
        $this->view->assign('searchCondition',$data);
        $this->view->assign('list_data',$list_data['data']);
        $this->view->assign('listData',$listData);
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());
        $this->view->assign('count',$count);
        if($request->isAjax()){
            $this->view->assign("is_ajax", '1');
            return $this->view->fetch('no_settlement_ajax');
        }else{
            return $this->view->fetch();
        }

    }

    /**
     * 结算编辑
     */
    public function settlement_edit(Request $request){

        if($request->isPost()){
            $data = input();

            if(!$data['id']){
                return ajax_return_adv_error('缺少参数');
            }

            $hotel_accommodation = Db::name('hotel_accommodation')->where('id',$data['id'])->field('id,subscription,unit_price,total_price,balance_payment')->find();

            if($data['account']){
                $arr = explode('-',$data['account']);
                $data['account'] = $arr[0];
            }
            if($data['subscription']){
                if($data['subscription'] != $hotel_accommodation['subscription']){
                    $data['is_change_subscription'] = 1;
                }
            }else{
                $data['subscription'] = $hotel_accommodation['subscription'];
            }
            if($data['total_price']){
                if($data['total_price'] != $hotel_accommodation['total_price']){
                    $data['is_change_total'] = 1;
                }
            }else{
                $data['total_price'] = $hotel_accommodation['total_price'];
            }
            $data['balance_payment'] = $data['total_price'] - $data['subscription'];

            $res =  Db::name('hotel_accommodation')->strict(false)->where('id',$data['id'])->update($data);

            if($res){
                return ajax_return_adv('修改成功');
            }else{
                return ajax_return_adv_error('修改失败');
            }

        }else{
            $data = input();
            if (!$data['id']) {
                return ajax_return_adv_error('缺少参数');
            }

            $hotel_accommodation =  Db::name('hotel_accommodation')->where('id',$data['id'])->find();

            if(!empty($hotel_accommodation)){
                $hotel_account = Db::name('hotel_account')->where('hotel_id',$hotel_accommodation['hotel_id'])->select();
            }else{
                $hotel_account = [];
            }

            $hotel_accommodation['hotel_name'] = Db::name('hotel')->where('id',$hotel_accommodation['hotel_id'])->value('hotel_name');
            $hotel_accommodation['hotel_room_name'] = Db::name('hotel_room_type')->where('id',$hotel_accommodation['hotel_room_type'])->value('room_name');
            $hotel_accommodation['days'] = round(($hotel_accommodation['end_date']-$hotel_accommodation['check_in_date'])/3600/24);
//            $hotel_accommodation['total_price'] = $hotel_accommodation['unit_price'] * $hotel_accommodation['days'];

            $this->view->assign('hotel_account',$hotel_account);
            $this->view->assign('data',$hotel_accommodation);
            return $this->view->fetch();
        }


    }

    /**
     * 申请结算
     */
    public function apply_settlement(){

        $id = input('id');

        if(!$id){
            return ajax_return_adv_error('参数有误');
        }

        $hotel_accommodation = Db::name('hotel_accommodation')->where('id',$id)->find();

        if(!$hotel_accommodation){
            return ajax_return_adv_error('不存在该住宿单信息');
        }
        if(!$hotel_accommodation['account']){
            return ajax_return_adv_error('请先完善该住宿单的结算信息');
        }else{
            if($hotel_accommodation['is_reject'] == 1){
                if(empty($hotel_accommodation['total_price'])){
                    $day = round(($hotel_accommodation['end_date']-$hotel_accommodation['check_in_date'])/3600/24);
                    $total_price = $hotel_accommodation['unit_price']*$day;
                }else{
                    $total_price = $hotel_accommodation['total_price'];
                }
                $balance_payment = $total_price - $hotel_accommodation['subscription'];
                $update_data = [
                    'is_apply_settlement'=>1,
                    'apply_time'=>time(),
                    'reject_time'=>null,
                    'reject_remark'=>null,
                    'is_reject'=>0,
                    'total_price'=>$total_price,
                    'balance_payment'=>$balance_payment,
                ];
                $res = Db::name('hotel_accommodation')->strict(false)->where('id',$id)->update($update_data);
            }else {
                $update_data = [
                    'is_apply_settlement'=>1,
                    'apply_time'=>time(),
                ];
                $res = Db::name('hotel_accommodation')->strict(false)->where('id',$id)->update($update_data);
            }
            if($res){
                return ajax_return_adv('申请结算成功');
            }else{
                return ajax_return_adv_error('申请结算失败');
            }
        }
    }

    /**
     * 取消申请结算
     */
    public function no_apply_settlement(){
        $id = input('id');
        if(!$id){
            return ajax_return_adv_error('参数有误');
        }

        $hotel_accommodation = Db::name('hotel_accommodation')->where('id',$id)->find();

        if(!$hotel_accommodation){
            return ajax_return_adv_error('不存在该住宿单信息');
        }
        $res = Db::name('hotel_accommodation')->strict(false)->where('id',$id)->update(['is_apply_settlement'=>0]);
        if($res){
            return ajax_return_adv('取消成功');
        }else{
            return ajax_return_adv_error('取消失败');
        }

    }

    /**
     * 批量申请结算
     */
    public function multi_apply_settlement(){
        $data = input();
        if(count($data['ck'])>0){
            $i = 0;
            $not_account = '';
            foreach ($data['ck'] as $k => $v){
                $hotel_accommodation = Db::name('hotel_accommodation')->where('id',$v['value'])->find();
                if($hotel_accommodation['account']){
                    if(empty($hotel_accommodation['total_price'])){
                        $day = round(($hotel_accommodation['end_date']-$hotel_accommodation['check_in_date'])/3600/24);
                        $total_price = $hotel_accommodation['unit_price']*$day;
                    }else{
                        $total_price = $hotel_accommodation['total_price'];
                    }
                    $balance_payment = $total_price - $hotel_accommodation['subscription'];
                    $update_data = [
                        'is_apply_settlement'=>1,
                        'apply_time'=>time(),
                        'reject_time'=>null,
                        'reject_remark'=>null,
                        'is_reject'=>0,
                        'total_price'=>$total_price,
                        'balance_payment'=>$balance_payment,
                    ];
                    Db::name('hotel_accommodation')->strict(false)->where('id',$v['value'])->update($update_data);
                }else{
                    if($v['value'] != 'all'){
                        $not_account .= $v['value']."+";
                    }
                }
                $i = $i+1;
            }
            if(!empty($not_account)){
                $not_account = rtrim($not_account,'+');
                return ajax_return_adv('申请结算成功,以下住宿单无法申请结算：'.$not_account.',原因：缺少结算信息');
            }else{
                return ajax_return_adv('申请结算成功');
            }

        }else{
            return ajax_return_adv_error('请先进行选择');
        }

    }

    /**
     * 批量编辑结算账户
     */
    public function multi_edit_settlement(){
        $data = input();
//        return ajax_return_adv('123123123','','','','',$data);
        if($data['edit'] && $data['edit'] == 1){
            if($data['edit2'] && $data['edit2'] == 1){//批量编辑
                $update_data = [];
                if($data['account']){
                    $arr = explode('-',$data['account']);
                    $update_data['account'] = $arr[0];
                    $update_data['account_name'] = $arr[1];
                    $update_data['account_bank'] = $arr[2];
                }else{
                    return ajax_return_adv_error('请选择账户信息');
                }
                if(!$data['ids']){
                    return ajax_return_adv_error('缺少参数');
                }
                $arr_ids = explode('+',$data['ids']);
                $fail_id = '';
                if(count($arr_ids)>1){
                    foreach ($arr_ids as $ka => $va){
                        $res = Db::name('hotel_accommodation')->strict(false)->where('id',$va)->update($update_data);
                        if(!$res){
                            $temp = Db::name('hotel_accommodation')->where('id',$va)->find();
                            if($temp['account'] != $update_data['account'] || $temp['account_name'] != $update_data['account_name'] || $temp['account_bank'] != $update_data['account_bank']){
                                $fail_id .= $va.'+';
                            }
                        }
                    }
                    if(!empty($fail_id)){
                        $fail_id = rtrim($fail_id,'+');
                    }
                }else{
                    $res = Db::name('hotel_accommodation')->strict(false)->where('id',$arr_ids[0])->update($update_data);
                    if(!$res){
                        $fail_id = $arr_ids[0];
                    }
                }
                if(!empty($fail_id)){
                    return ajax_return_adv_error('住宿单号为：'.$fail_id.'，结算编辑失败');
                }else{
                    return ajax_return_adv('批量编辑成功');
                }
            }else{//进行批量编辑页面
                if(!$data['hotel_id'] || !$data['ids']){
                    return ajax_return_adv_error('缺少参数');
                }
                $hotel_account = Db::name('hotel_account')->where('hotel_id',$data['hotel_id'])->select();
                $hotel_accommodation['hotel_name'] = Db::name('hotel')->where('id',$data['hotel_id'])->value('hotel_name');
                $this->view->assign('hotel_account',$hotel_account);
                $this->view->assign('data',$hotel_accommodation);
                $this->view->assign('ids',$data['ids']);
                return $this->view->fetch();
            }
        }else{
            if(!$data['ck'] || count($data['ck']) < 1){
                return ajax_return_adv_error('请先进行选择');
            }
            //检查酒店信息是否一致
            if($data['check'] == 1){
                $hotel_ids = [];
                $ids = '';
                foreach ($data['ck'] as $k => $v){
                    $hotel_id = Db::name('hotel_accommodation')->where('id',$v['value'])->value('hotel_id');
                    $hotel_ids[$hotel_id] = true;
                    $ids .= $v['value'].'+';
                }
                $ids = rtrim($ids,'+');
                $hotel_num = array_keys($hotel_ids);
                if(count($hotel_num)>1){
                    return ajax_return_adv_error('酒店信息不一致，不可进行批量编辑！');
                }
                $res['code'] = 1;
                $res['hotel_id'] = $hotel_num[0];
                $res['ids'] = $ids;
                return $res;
            }else{
                return ajax_return_adv_error('页面出错，请重新刷新页面');
            }
        }
    }

    /**
     * 修改页面
     */
    public function deal()
    {

        $id = input('id');
        $group_id = input('group_id');
        //获取已组合的数据
        $data = input();

        if (!$data['id']) {
            return ajax_return_adv_error('缺少必要的参数');
        }
        if (!$group_id) {
            return ajax_return_adv_error('缺少必要的参数');
        }
        $id = $data['id'];
        // 从住宿列表查找相关信息
        $hotelAccommodation = Db::name('hotel_accommodation')->where('portion_traveler_id',$data['id'])->select();
        $room_types = [];
        if ($hotelAccommodation){
            foreach ($hotelAccommodation as $index => $item) {
                $hotelAccommodation[$index]['realname'] = Db::name('admin_user')->where('id',$item['driver_user_id'])->value('realname');
                $hotelAccommodation[$index]['check_in_date'] = empty($item['check_in_date'])?'':date('Y-m-d',$item['check_in_date']);
                $hotelAccommodation[$index]['end_date'] = empty($item['end_date'])?'':date('Y-m-d',$item['end_date']);
                $orderTravellers = Db::name('order_traveler')->where('id','in',$item['order_travel_ids'])->field('id,name,accommodation')->select();
                $userName = '';
                $remark = '';
                if ($orderTravellers){
                    foreach ($orderTravellers as $index01 => $orderTraveller) {
                        $userName .= "{$orderTraveller['id']}:{$orderTraveller['name']}+";
                        $remark .= "{$orderTraveller['id']}:{$orderTraveller['accommodation']}+";
                    }
                }
                $hotelAccommodation[$index]['name'] = rtrim($userName,'+');
                $hotelAccommodation[$index]['remark'] = rtrim($remark,'+');
                // 查找路线名称
                $routeName = Db::name('route')->where('id',$item['route_id'])->value('title');
                $hotelAccommodation[$index]['route_name'] = empty($routeName)? '该旅游路线不存在':$routeName;
                // 根据酒店id查找当前酒店的所有房型
                $roomTypes = Db::name('room_hotel_number')->where('hotel_id',$item['hotel_id'])->select();
                if ($roomTypes){
                    foreach ($roomTypes as $index02 => $roomType) {
                        $routeName = Db::name('hotel_room_type')->where('id',$roomType['room_type_id'])->value('room_name');
                        $roomTypes[$index02]['room_name'] = empty($routeName) ? '房型不存在':$routeName;
                    }
                }
                $hotelAccommodation[$index]['roomTypes'] = $roomTypes;
            }
        }
        // 查找所有酒店
        $hotel = Db::name('hotel')->field('id,hotel_name')->select();
//            dump($hotelAccommodation);
        $this->view->assign('group_id',$group_id);
        return view('',compact('hotelAccommodation','hotel','roomTypes','id'));
    }

    /**
     * 修改页面数据
     */
    public function deals()
    {
        $data = input();
        // 根据派单id查找住宿信息
        $portionInfo = Db::name('portion_traveler')->where('id',$data['id'])->find();
        if (!$portionInfo){
            return ajax_return_adv_error('不存在该住宿派单信息');
        }
        // 从住宿列表查找相关信息
        $hotelAccommodation = Db::name('hotel_accommodation')->where('is_complete',0)->where('portion_traveler_id',$portionInfo['id'])->select();
        if ($hotelAccommodation){
            foreach ($hotelAccommodation as $index => $item) {
                $hotelAccommodation[$index]['realname'] = Db::name('admin_user')->where('id',$item['driver_user_id'])->value('realname');
                $hotelAccommodation[$index]['check_in_date'] = empty($item['check_in_date'])?'':date('Y-m-d',$item['check_in_date']);
                $hotelAccommodation[$index]['end_date'] = empty($item['end_date'])?'':date('Y-m-d',$item['end_date']);
                $orderTravellers = Db::name('order_traveler')->where('id','in',$item['order_travel_ids'])->field('id,name,accommodation')->select();
                $userName = '';
                $remark = '';
                if ($orderTravellers){
                    foreach ($orderTravellers as $index01 => $orderTraveller) {
                        $userName .= "{$orderTraveller['id']}:{$orderTraveller['name']}+";
                        $remark .= "{$orderTraveller['id']}:{$orderTraveller['accommodation']}+";
                    }
                }
                $hotelAccommodation[$index]['name'] = rtrim($userName,'+');
                $hotelAccommodation[$index]['remark'] = rtrim($remark,'+');
                // 查找路线名称
                $routeName = Db::name('route')->where('id',$item['route_id'])->value('title');
                $hotelAccommodation[$index]['route_name'] = empty($routeName)? '该旅游路线不存在':$routeName;
                // 根据酒店id查找当前酒店的所有房型
                $roomTypes = Db::name('room_hotel_number')->where('hotel_id',$item['hotel_id'])->select();
                if ($roomTypes){
                    foreach ($roomTypes as $index02 => $roomType) {
                        $routeName = Db::name('hotel_room_type')->where('id',$roomType['room_type_id'])->value('room_name');
                        $roomTypes[$index02]['room_name'] = empty($routeName) ? '房型不存在':$routeName;
                    }
                }
            }
        }
        // 查找所有酒店
        $hotel = Db::name('hotel')->field('id,hotel_name')->select();
        $result['hotelAccommodation'] = $hotelAccommodation;
        $result['roomTypes'] = $roomTypes;
        $result['hotel'] = $hotel;
        return ajax_return_adv('获取数据成功', '','','','',$result);
    }

    /**
     * 修改的添加操作
     */
    public function increase()
    {
        $data = input();

        // 从住宿列表查找相关信息
        $hotelAccommodation = Db::name('hotel_accommodation')->where('id',$data['id'])->select();
        if ($hotelAccommodation){
            foreach ($hotelAccommodation as $index => $item) {
                $hotelAccommodation[$index]['realname'] = Db::name('admin_user')->where('id',$item['driver_user_id'])->value('realname');
                $hotelAccommodation[$index]['check_in_date'] = empty($item['check_in_date'])?'':date('Y-m-d',$item['check_in_date']);
                $hotelAccommodation[$index]['end_date'] = empty($item['end_date'])?'':date('Y-m-d',$item['end_date']);
                $orderTravellers = Db::name('order_traveler')->where('id','in',$item['order_travel_ids'])->field('id,name,accommodation')->select();
                $userName = '';
                $remark = '';
                if ($orderTravellers){
                    foreach ($orderTravellers as $index01 => $orderTraveller) {
                        $userName .= "{$orderTraveller['id']}:{$orderTraveller['name']}+";
                        $remark .= "{$orderTraveller['id']}:{$orderTraveller['accommodation']}+";
                    }
                }
                $hotelAccommodation[$index]['name'] = rtrim($userName,'+');
                $hotelAccommodation[$index]['remark'] = rtrim($remark,'+');
                // 查找路线名称
                $routeName = Db::name('route')->where('id',$item['route_id'])->value('title');
                $hotelAccommodation[$index]['route_name'] = empty($routeName)? '该旅游路线不存在':$routeName;
                // 根据酒店id查找当前酒店的所有房型
                $roomTypes = Db::name('room_hotel_number')->where('hotel_id',$item['hotel_id'])->select();
                if ($roomTypes){
                    foreach ($roomTypes as $index02 => $roomType) {
                        $routeName = Db::name('hotel_room_type')->where('id',$roomType['room_type_id'])->value('room_name');
                        $roomTypes[$index02]['room_name'] = empty($routeName) ? '房型不存在':$routeName;
                    }
                }
            }
        }
        // 查找所有酒店
        $hotel = Db::name('hotel')->field('id,hotel_name')->select();
        $result['hotelAccommodation'] = $hotelAccommodation;
        $result['roomTypes'] = $roomTypes;
        $result['hotel'] = $hotel;
        return ajax_return_adv('获取数据成功', '','','','',$result);
    }

    /**
     * 数据修改完成
     */
    public function addTraveller(){
        $data = input();
        dump($data);
        return ajax_return_adv('123');
        $len = count($data['groupIds']); // 数组的长度
        $groupInfo = Db::name('dispatch_traveler_group')->where('id',$data['groupIds'][0])->find();
        // 组装组合和信息
        $content = "您好,你的派单编号为{$groupInfo['id']}的乘客住宿信息是: ".PHP_EOL;
        $inse = 0;
        for ($i = 0; $i < $len; $i++){
            // 查询司机的用户id
            $group = Db::name('dispatch_traveler_group')->where('id',$data['groupIds'][$i])->find();
            // 从订单表获取旅游路线id
            $old_id = Db::name('order_traveler')->where('group_id',$data['groupIds'][$i])->value('oid');
            $route_id = Db::name('order')->where('id',$old_id)->value('route_id');
            if (strtotime($data['check_in_date'][$i]) > strtotime($data['end_date'][$i])){ // 入住日期不能大于退房日期
                $group_count = $i + 1;
                return ajax_return_adv_error("第{$group_count}组合入住日期不能大于退房日期");
            }

            if(!empty($data['ids'][$i])) {//需要修改的数据
                $updata = [
                    'check_in_date'=>strtotime($data['check_in_date'][$i]),
                    'end_date'=>strtotime($data['end_date'][$i]),
                    'hotel_id'=>$data['hotel_id'][$i],
                    'hotel_room_type'=>$data['room_type_id'][$i]
                ];
                $getIds = Db::name('hotel_accommodation')
                    ->strict(false)
                    ->where('id', $data['ids'][$i])
                    ->update($updata);

            } else { //需要添加的数据
                $acc = Db::name('hotel_accommodation')->where('id',$data['tjid'][$inse])->find(); // 批量插入旅客住宿列表
                $inse +=1;
                //查询单价(酒店协价)
                $maps['isdelete'] = ['<>',1];
                $maps['hotel_id'] = $data['hotel_id'][$i];
                $htpr = Db::name('hotel_time_price')->where($maps)->order('id','desc')->select();

                foreach ($htpr as $k =>$v) {
                    if(strtotime($v['start_time']) <= strtotime($data['check_in_date'][$i]) && strtotime($v['end_time']) >= strtotime($data['end_date'][$i])){
                        $unit_price = Db::name('hotel_room_price')->where('isdelete',0)->where('hotel_time_price_id',$v['id'])->value('room_price');
                    }
                }
                $insert[] = [
                    'group_id'=>$data['groupIds'][$i],
                    'driver_user_id'=>$acc['driver_user_id'],
                    'check_in_date'=>strtotime($data['check_in_date'][$i]),
                    'end_date'=>strtotime($data['end_date'][$i]),
                    'hotel_id'=>$data['hotel_id'][$i],
                    'hotel_room_type'=>$data['room_type_id'][$i],
                    'order_travel_ids'=>$acc['order_travel_ids'],
                    'unit_price'=>$unit_price,
                    'route_id'=>$acc['route_id'],
                    'create_time' => time(),
                    'portion_traveler_id' => $acc['portion_traveler_id'],
                ];

                $travelers = Db::name('order_traveler')->where('id','in',$data['order_travel_ids'][$i])->select();
                if ($travelers){
                    $username = '';
                    $phone = ''; // 旅客手机号码
                    for ($j=0; $j < count($travelers); $j++){
                        $username .= $travelers[$j]['name'].'、';
                        $phone .= $travelers[$j]['phone'].'、';
                    }
                    $hotel = Db::name('hotel')->where('id',$data['hotel_id'][$i])->find();
                    $hotel_name = $hotel['hotel_name'];
                    $location = $hotel['hotel_location'];
                    $type_name = Db::name('hotel_room_type')->where('id',$data['room_type_id'][$i])->value('room_name');
                    $username = rtrim($username,'、');
                    $phone = rtrim($phone,'、');
                    if (strlen($phone) < 5){
                        $phone = '';
                    }
                    $content = "组合为:{$username},".PHP_EOL;
                    $content .= "联系电话为:{$phone},".PHP_EOL;
                    $content .= "他们的住宿时间为:{$data['check_in_date'][$i]}-{$data['end_date'][$i]},".PHP_EOL;
                    $content .= "酒店的名称为:{$hotel_name},".PHP_EOL;
                    $content .= "房间类型为:{$type_name},".PHP_EOL;
                    $content .= "酒店的地址为:{$location}。".PHP_EOL;
                }
            }

        }

        if (empty($insert)){
            $insert = [];
        }

        // 添加数据到表
        $getIds = Db::name('hotel_accommodation')->strict(false)->insertAll($insert); // 批量插入旅客住宿列表
        if ($getIds){
            logs('addRecord',$insert);
            $this->travellerInfos = $insert;
            // 添加酒店的使用记录
            $this->addRecord();
            // 更改住宿派单状态
            Db::name('portion_traveler')->where('id',$data['order'])->update(['isdeal'=>1]);
            // 发送短信给司机
            $sendMsg = [
                'user_id'=>$groupInfo['driver_user_id'],
                'title'=> '旅客住宿安排',
                'content'=>$content,
                'dispatch_traveler_group_id'=>$data['group_id'][0],
                'create_time'=>NOW_TIME,
                'type'=>'system_ordinary_info',
            ];
            logs('sendMsg',$sendMsg);
            logs('zhusupaidanxinxi',$content);
            if (strlen($content) > 300){
                $content = mb_substr($content,0,300);
            }
            Db::name('notify')->strict(false)->insert($sendMsg);
            // 发送短息
            umeng_send($groupInfo['driver_user_id'],'旅客住宿安排',$content);
            return ajax_return_adv('分配房间成功, 短信已发送');
        }else{
            return ajax_return_adv_error('分配房间失败');
        }
    }

    /**
     * 数据修改完成_修改
     */
    public function editTraveller(){
        $data = input();

        $len = count($data['groupIds']); // 数组的长度
        $groupInfo = Db::name('dispatch_traveler_group')->where('id',$data['groupIds'][0])->find();
        // 组装组合和信息
        $content = "您好,你的派单编号为{$groupInfo['id']}的乘客住宿信息是: ".PHP_EOL;
        $inse = 0;
        if(!$data['ids'] || !$data['group_id']){
            return ajax_return_adv_error('缺少参数');
        }

        $insert = [];
        $update_res = false;
        $add_res = false;

        for ($i = 0; $i < $len; $i++){
            //获取酒店信息
            $hotel = Db::name('hotel')->where('id',$data['hotel_id'][$i])->find();
            $hotel_name = $hotel['hotel_name'];
            $location = $hotel['hotel_location'];

            if(!empty($data['ids'][$i])){
                if($data['group_id'] == $data['ids'][$i]){//修改住宿单信息

                    $unit_price = '';
                    $maps['isdelete'] = ['<>',1];
                    $maps['hotel_id'] = $data['hotel_id'][$i];
                    //获取酒店协价信息
                    $htpr = Db::name('hotel_time_price')->where($maps)->order('id','desc')->select();

                    //获取房型单价
                    foreach ($htpr as $k =>$v) {
                        if(strtotime($v['start_time']) <= strtotime($data['check_in_date'][$i]) && strtotime($v['end_time']) >= strtotime($data['end_date'][$i])){
                            $unit_price = Db::name('hotel_room_price')->where('isdelete',0)->where('hotel_time_price_id',$v['id'])->value('room_price');
                        }
                    }

                    if(empty($unit_price)){
                        return ajax_return_adv_error($hotel_name."在".$data['check_in_date'][$i]."至".$data['end_date'][$i].'时间内，不存在酒店协价信息');
                    }

                    $updata = [
                        'check_in_date'=>strtotime($data['check_in_date'][$i]),
                        'end_date'=>strtotime($data['end_date'][$i]),
                        'hotel_id'=>$data['hotel_id'][$i],
                        'unit_price'=>$unit_price,
                        'hotel_room_type'=>$data['room_type_id'][$i]
                    ];

                    $rule = [
                        'check_in_date' => 'require',
                        'end_date' => 'require',
                        'hotel_id' => 'require',
                        'hotel_room_type' => 'require',
                    ];
                    $message = [
                        'check_in_date.require' => '入住日期不能为空',
                        'end_date.require' => '结束日期不能为空',
                        'hotel_id.require' => '酒店名称不能为空',
                        'hotel_room_type.require' => '酒店房型不能为空',
                    ];
                    $valdate = new Validate($rule, $message);
                    $result = $valdate->check($updata);
                    if (!$result){
                        return ajax_return_adv_error($valdate->getError());
                    }
                    //判断修改的日期
                    if(strtotime($data['check_in_date'][$i]) > strtotime($data['end_date'][$i])){
                        return ajax_return_adv_error("第{".($i+1)."}组合入住日期不能大于退房日期");
                    }


                    $update_res = Db::name('hotel_accommodation')
                                ->strict(false)
                                ->where('id', $data['ids'][$i])
                                ->update($updata);

                    $acc = Db::name('hotel_accommodation')->where('id',$data['ids'][$i])->find();
                    $travelers = Db::name('order_traveler')->where('id','in',$acc['order_travel_ids'][$i])->select();
                    if ($travelers){
                        $username = '';
                        $phone = ''; // 旅客手机号码
                        for ($j=0; $j < count($travelers); $j++){
                            $username .= $travelers[$j]['name'].'、';
                            $phone .= $travelers[$j]['phone'].'、';
                        }
                        $type_name = Db::name('hotel_room_type')->where('id',$data['room_type_id'][$i])->value('room_name');
                        $username = rtrim($username,'、');
                        $phone = rtrim($phone,'、');
                        if (strlen($phone) < 5){
                            $phone = '';
                        }
                        $content = "组合为:{$username},".PHP_EOL;
                        $content .= "联系电话为:{$phone},".PHP_EOL;
                        $content .= "他们的住宿时间为:{$data['check_in_date'][$i]}-{$data['end_date'][$i]},".PHP_EOL;
                        $content .= "酒店的名称为:{$hotel_name},".PHP_EOL;
                        $content .= "房间类型为:{$type_name},".PHP_EOL;
                        $content .= "酒店的地址为:{$location}。".PHP_EOL;
                    }

                    $num = round((strtotime($data['end_date'][$i])-strtotime($data['check_in_date'][$i]))/3600/24);

                    //修改房间记录
                    Db::name('room_consumption')
                       ->where('hotel_id',$acc['hotel_id'])
                       ->where('hotel_room_type_id',$acc['room_type_id'])
                       ->where('date_of_stay',$acc['check_in_date'][$i])
                       ->update(['date_of_stay'=>$data['check_in_date'][$i],'num'=>$num]);
                }else{
                    $updata = [
                        'groupIds' => $data['groupIds'][$i],
                        'ids' => $data['groupIds'][$i],
                        'check_in_date' => $data['groupIds'][$i],
                        'end_date' => $data['groupIds'][$i],
                        'hotel_id' => $data['groupIds'][$i],
                        'room_type_id' => $data['groupIds'][$i]
                    ];
                    unset($data['groupIds'][$i]);
                    unset($data['ids'][$i]);
                    unset($data['check_in_date'][$i]);
                    unset($data['end_date'][$i]);
                    unset($data['hotel_id'][$i]);
                    unset($data['room_type_id'][$i]);
                }
            }else{//不存在ids,则为新增数据

                $updata = [
                    'check_in_date'=>strtotime($data['check_in_date'][$i]),
                    'end_date'=>strtotime($data['end_date'][$i]),
                    'hotel_id'=>$data['hotel_id'][$i],
                    'hotel_room_type'=>$data['room_type_id'][$i]
                ];
                $rule = [
                    'check_in_date' => 'require',
                    'end_date' => 'require',
                    'hotel_id' => 'require',
                    'hotel_room_type' => 'require',
                ];
                $message = [
                    'check_in_date.require' => '入住日期不能为空',
                    'end_date.require' => '结束日期不能为空',
                    'hotel_id.require' => '酒店名称不能为空',
                    'hotel_room_type.require' => '酒店房型不能为空',
                ];
                $valdate = new Validate($rule, $message);
                $result = $valdate->check($updata);
                if (!$result){
                    return ajax_return_adv_error($valdate->getError());
                }
                //判断修改的日期
                if(strtotime($data['check_in_date'][$i]) > strtotime($data['end_date'][$i])){
                    return ajax_return_adv_error("第{".($i+1)."}组合入住日期不能大于退房日期");
                }

                $acc = Db::name('hotel_accommodation')->where('id',$data['tjid'][$inse])->find(); // 批量插入旅客住宿列表
                $inse +=1;

                $unit_price = '';
                $maps['isdelete'] = ['<>',1];
                $maps['hotel_id'] = $data['hotel_id'][$i];
                //获取酒店协价信息
                $htpr = Db::name('hotel_time_price')->where($maps)->order('id','desc')->select();

                //获取房型单价
                foreach ($htpr as $k =>$v) {
                    if(strtotime($v['start_time']) <= strtotime($data['check_in_date'][$i]) && strtotime($v['end_time']) >= strtotime($data['end_date'][$i])){
                        $unit_price = Db::name('hotel_room_price')->where('isdelete',0)->where('hotel_time_price_id',$v['id'])->value('room_price');
                    }
                }

                if(empty($unit_price)){
                    return ajax_return_adv_error($hotel_name."在".$data['check_in_date'][$i]."至".$data['end_date'][$i].'时间内，不存在酒店协价信息');
                }

                //整合插入的数据
                $insert[] = [
                    'group_id'=>$acc['group_id'], //获取分组ID
                    'driver_user_id'=>$acc['driver_user_id'], //获取司机id
                    'check_in_date'=>strtotime($data['check_in_date'][$i]),//入住日期 退房日期 酒店id 房型id
                    'end_date'=>strtotime($data['end_date'][$i]),
                    'hotel_id'=>$data['hotel_id'][$i],
                    'hotel_room_type'=>$data['room_type_id'][$i],
                    'order_travel_ids'=>$acc['order_travel_ids'],//订单旅客id
                    'unit_price'=>$unit_price,
                    'route_id'=>$acc['route_id'],//线路id
                    'create_time' => time(),
                    'portion_traveler_id' => $acc['portion_traveler_id'], //派单id
                ];

                $travelers = Db::name('order_traveler')->where('id','in',$acc['order_travel_ids'][$i])->select();
                if ($travelers){
                    $username = '';
                    $phone = ''; // 旅客手机号码
                    for ($j=0; $j < count($travelers); $j++){
                        $username .= $travelers[$j]['name'].'、';
                        $phone .= $travelers[$j]['phone'].'、';
                    }
                    $type_name = Db::name('hotel_room_type')->where('id',$data['room_type_id'][$i])->value('room_name');
                    $username = rtrim($username,'、');
                    $phone = rtrim($phone,'、');
                    if (strlen($phone) < 5){
                        $phone = '';
                    }
                    $content = "组合为:{$username},".PHP_EOL;
                    $content .= "联系电话为:{$phone},".PHP_EOL;
                    $content .= "他们的住宿时间为:{$data['check_in_date'][$i]}-{$data['end_date'][$i]},".PHP_EOL;
                    $content .= "酒店的名称为:{$hotel_name},".PHP_EOL;
                    $content .= "房间类型为:{$type_name},".PHP_EOL;
                    $content .= "酒店的地址为:{$location}。".PHP_EOL;
                }
            }

            //插入数据
            if(count($insert)>0){
                // 添加数据到表
                $add_res = Db::name('hotel_accommodation')->strict(false)->insertAll($insert);

                if($add_res){
                    logs('addRecord',$insert);
                    $this->travellerInfos = $insert;
                    // 添加酒店的使用记录
                    $this->addRecord();
                    // 更改住宿派单状态
                    Db::name('portion_traveler')->where('id',$data['order'])->update(['isdeal'=>1]);
                    // 发送短信给司机
                    $sendMsg = [
                        'user_id'=>$groupInfo['driver_user_id'],
                        'title'=> '旅客住宿安排',
                        'content'=>$content,
                        'dispatch_traveler_group_id'=>$data['group_id'][0],
                        'create_time'=>NOW_TIME,
                        'type'=>'system_ordinary_info',
                    ];
                    logs('sendMsg',$sendMsg);
                    logs('zhusupaidanxinxi',$content);
                    if (strlen($content) > 300){
                        $content = mb_substr($content,0,300);
                    }
                    Db::name('notify')->strict(false)->insert($sendMsg);
                    // 发送短息
                    umeng_send($groupInfo['driver_user_id'],'旅客住宿安排',$content);
                }
            }
        }
        if($add_res || $update_res){
            return ajax_return_adv('分配房间成功, 短信已发送');
        }else{
            if($data['tjid']){
                return ajax_return_adv_error('房间添加失败');
            }else{
                return ajax_return_adv_error('房间更新失败，无数据变化');
            }
        }
    }

    /**
     * 添加酒店房间的使用记录
     */
    public function addRecord()
    {
        logs('zhusu',$this->travellerInfos);
        $data = $this->travellerInfos;
        foreach ($data as $index => $val) {
            $tian = round(($val['end_date']-$val['check_in_date'])/3600/24);
            // 当前的入住日期
            $check_in_date = date('Y-m-d',$val['check_in_date']);
            // 把入住日期与退房日期的相差天数
            $date = [$check_in_date];
            logs('cha',$date);
            for ($i=1; $i<= $tian; $i++){
                array_push($date,date("Y-m-d",strtotime("+{$i} day",strtotime("{$check_in_date}"))));//添加的
            }
            // 查找当前的酒店是否有住宿记录
            if ($date){
                foreach ($date as $index => $item) {
                    $find = Db::name('room_consumption')->where('hotel_id',$val['hotel_id'])->where('hotel_room_type_id',$val['hotel_room_type'])
                        ->where('date_of_stay',$item)->find();
                    if (!$find){
                        $insert = [
                            'hotel_id'=>$val['hotel_id'],
                            'hotel_room_type_id'=>$val['hotel_room_type'],
                            'date_of_stay'=>$item,
                            'create_time'=>time(),
                            'num'=>1,
                        ];
                        $addId = Db::name('room_consumption')->strict(false)->insertGetId($insert);
                        logs('zhusulog',$addId);
                    }else{
                        $num = $find['num']+1;
                        $up = Db::name('room_consumption')->where('hotel_id',$val['hotel_id'])->where('hotel_room_type_id',$val['hotel_room_type'])
                            ->where('date_of_stay',$item)->update(['num'=>$num]);
                        logs('upzhusulog', $up);
                    }
                }
            }
        }
    }

    /**
     * 批量取消结算
     */
    public function multi_no_settlement(){

        $data = input();

        if(!$data['ck'] || count($data['ck']) < 1){
            return ajax_return_adv_error('请先勾选');
        }
        $un_set = '';
        $fail_res = '';
        $str = '';
        foreach ($data['ck'] as $k => $v){

            $hotel_accommodation = Db::name('hotel_accommodation')->where('id',$v)->find();

            if(!$hotel_accommodation){
                $un_set .= $v.'、';
            }

            $res = Db::name('hotel_accommodation')->strict(false)->where('id',$v)->update(['is_apply_settlement'=>0]);

            if(!$res){
                $fail_res .= $v.'、';
            }
        }

        if(!empty($un_set)){
            $un_set = rtrim($un_set,'、');
            $un_set = $un_set.'不存在住宿单。';
            $str = $un_set;
        }
        if(!empty($fail_res)){
            $fail_res = rtrim($fail_res,'、');
            $fail_res = $fail_res.'取消失败。';
            if(!empty($str)){
                $str .= $fail_res;
            }else{
                $str = $fail_res;
            }
        }

        if(empty($str)){
            $str = '操作成功';
        }
        return ajax_return_adv($str);
    }

    /**
     * 检查确认结算信息
     */
    public function check_confirm_settlement(){

        $data = input();

        if(!$data['id']){
            return ajax_return_error('缺少参数id');
        }

        $hotel_accommodation = Db::name('hotel_accommodation')->where('id',$data['id'])->find();

        if($data['type'] && $data['type'] == 'check') {

            if(!$hotel_accommodation){
                return ajax_return_adv_error('不存在该住宿单信息');
            }

            if ($hotel_accommodation['is_complete'] == '0') {
                return ajax_return_error('住宿未完成');
            }

            if ($hotel_accommodation['is_settlement'] == '1') {
                return ajax_return_error('该住宿单已结算');
            }

            return ajax_return('ok');
        }
    }

    /**
     * 确认结算
     */
    public function confirm_settlement(Request $request){
        $data = input();

        if(!$data['id']){
            return ajax_return_error('缺少参数id');
        }

        $hotel_accommodation = Db::name('hotel_accommodation')->where('id',$data['id'])->find();

        if($request->isAjax()){

            if(!$hotel_accommodation){
                return ajax_return_adv_error('不存在该住宿单信息');
            }

            if ($hotel_accommodation['is_complete'] == '0') {
                return ajax_return_error('住宿未完成');
            }

            if ($hotel_accommodation['is_settlement'] == '1') {
                return ajax_return_error('该住宿单已结算');
            }

            if (!$hotel_accommodation['driver_user_id']) {
                return ajax_return_error('未分配司导');
            }

            if($data['account']){
                $arr = explode('-',$data['account']);
                $data['account'] = $arr[0];
            }

            $rule = [
                'account' => 'require',
                'account_name' => 'require',
                'account_bank' => 'require',
                'settlement_mode' => 'require',
            ];
            $message = [
                'account.require' => '账号不能为空',
                'account_name.require' => '账号姓名不能为空',
                'account_bank.require' => '账号开户行不能为空',
                'settlement_mode.require' => '结算方式不能为空',
            ];
            $valdate = new Validate($rule, $message);
            $result = $valdate->check($data);
            if (!$result){
                return ajax_return_adv_error($valdate->getError());
            }

            //开启事务
            Db::startTrans();
            try {
                if(empty($hotel_accommodation['total_price'])){
                    $day = round(($hotel_accommodation['end_date']-$hotel_accommodation['check_in_date'])/3600/24);
                    $hotel_accommodation['total_price'] = $hotel_accommodation['unit_price']*$day;
                }
                $balance_payment = $hotel_accommodation['total_price'] - $hotel_accommodation['subscription'];
                $updata['apply_time'] = time();
                $updata['total_price'] = $hotel_accommodation['total_price'];
                $updata['balance_payment'] = $balance_payment;
                $updata['settlement_time'] = time();
                $updata['is_apply_settlement'] = 0;
                $updata['is_settlement'] = 1;
                $updata['settlement_money'] = $balance_payment;
                $updata['account'] = $data['account'];
                $updata['account_name'] = $data['account_name'];
                $updata['account_bank'] = $data['account_bank'];
                $updata['settlement_mode'] = $data['settlement_mode'];

                $result = Db::name('hotel_accommodation')
                    ->where('id', $data['id'])
                    ->strict(false)
                    ->update($updata);

                if ($result) {
                    Db::commit();
                    return ajax_return_adv('结算成功');
                }else{
                    Db::rollback();
                    return ajax_return_error('结算失败或已结算');
                }
            } catch (\Exception $e) {
                Db::rollback();
                return ajax_return_adv_error($e->getMessage());
            }
        }else{
            if(!empty($hotel_accommodation)){
                $hotel_account = Db::name('hotel_account')->where('hotel_id',$hotel_accommodation['hotel_id'])->select();
            }else{
                $hotel_account = [];
            }

            $hotel_accommodation['hotel_name'] = Db::name('hotel')->where('id',$hotel_accommodation['hotel_id'])->value('hotel_name');
            $hotel_accommodation['hotel_room_name'] = Db::name('hotel_room_type')->where('id',$hotel_accommodation['hotel_room_type'])->value('room_name');
            $hotel_accommodation['days'] = round(($hotel_accommodation['end_date']-$hotel_accommodation['check_in_date'])/3600/24);

            $this->view->assign('hotel_account',$hotel_account);
            $this->view->assign('data',$hotel_accommodation);
            return $this->view->fetch();
        }
    }

}
